package com.tarena.lbs.basic.web.filters;

import com.tarena.lbs.basic.web.utils.AuthenticationContextUtils;
import com.tarena.lbs.common.passport.encoder.JwtEncoder;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@Slf4j
public class AuthenticationFilter implements Filter {

    private static final String AUTHORIZATION = "Authorization";
    @Autowired
    private JwtEncoder<UserPrinciple> jwtEncoder;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        UserPrinciple userPrinciple = null;
        if (servletRequest instanceof HttpServletRequest){
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String jwt = request.getHeader(AUTHORIZATION);
            if (jwt != null && jwt.length() > 0){
                try {
                    userPrinciple = jwtEncoder.getLoginFromToken(jwt, UserPrinciple.class);
                }catch (Exception e){
                    log.error("携带的jwt解析失败",e);
                }
            }
        }
        AuthenticationContextUtils.set(userPrinciple);
        filterChain.doFilter(servletRequest,servletResponse);
        AuthenticationContextUtils.clear();
    }
}
